//
//  LXLHomeViewController.swift
//  Weibo-YQY-test
//
//  Created by Lang on 10/9/15.
//  Copyright © 2015 Lang. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class LXLHomeViewController: UITableViewController, LXLPopViewDelegate {

    private let CELL_ID = "home_cell_id"
    
    //保存当前 tableView 里面显示的数据
    lazy var statusArray: [LXLStatus] = [LXLStatus]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        
        

//        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "navigationbar_pop"), style: UIBarButtonItemStyle.Plain, target: self, action: "push")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.item("navigationbar_friendsearch", target: self, action: "push")
        navigationItem.rightBarButtonItem = UIBarButtonItem.item("navigationbar_pop", target: self, action: "push")
    
    
        setTitleButton()
        
        
        //设置 tableView
        setupTableView()
        
        
        self.tabBarItem.badgeValue = "10"
        
        //拿到显示 badgeValue 的控件
        
    }

    
    //注册一个 cell
    private func setupTableView(){
        //注册一个 cell
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: CELL_ID)
        // 上拉加载控件
        self.tableView.tableFooterView = pullupView
        //下拉刷新的控件
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        
        //请求数据
        loadData()
    }
    
    
    
    @objc private func push(){
        navigationController?.pushViewController(LXLTempViewController(), animated: true)
    }
    
    
    
    
    //设置顶部的标题按钮
    private func setTitleButton(){
        //初始化
        let titleButton = LXLHomeTitleButton()
        //设置点击事件
         titleButton.addTarget(self, action: "titleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
//        titleButton.backgroundColor = UIColor.orangeColor()
        // 设置文字以及图片
        titleButton.setTitle(LXLUserAccount.loadUserAccount()?.name ?? "首页", forState: UIControlState.Normal)
        
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected)
        
        //设置文字颜色
        titleButton.setTitleColor(RGB(r: 80, g: 80, b: 80), forState: UIControlState.Normal)
        // 设置大小，会以内容多大，就会把控件的大小调整到多大
        titleButton.sizeToFit()
        
        navigationItem.titleView = titleButton
        
        
    }
    
    
    
    //顶部 title 的点击事件
    @objc private func titleButtonClick(button: UIButton){
        printLog("点击了 titleButton")
        button.selected = !button.selected
        
//        // 添加一个遮罩
//        let coverButton = UIButton()
//        coverButton.addTarget(self, action: "converButtonClick:", forControlEvents: .TouchUpInside)
//        coverButton.size = CGSizeMake(SCREENW, SCREENH)
//        coverButton.backgroundColor = UIColor(white: 0, alpha: 0.1)
//        
//        
//        let window = UIApplication.sharedApplication().windows.last
//        window?.addSubview(coverButton)
        
        // 要弹出什么内容是当前 controller要关心的
        let contentView = UIView()
        contentView.backgroundColor = UIColor.redColor()
        contentView.size = CGSizeMake(150, 150)
        
        
        let view = LXLPopView(customView: contentView)
        view.delegate = self
        view.show(button)
    }
    // 实现 popView 的代理方法，当 popView 消失时就会调用
    func popViewWillDismiss() {
        let button = navigationItem.titleView as! UIButton
        button.selected = false
    }
    
    
   
    
    
    
    //请求数据
    @objc private func loadData(){
        let manager = AFHTTPSessionManager()
        
        //地址
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //参数
        var params = ["access_token":LXLUserAccount.loadUserAccount()!.access_token!]
        
        //如果是上拉加载,添加一个新的参数max_id
        if pullupView.isAnimating(){
            
            if let status = statusArray.last{
                //取到当前界面上最后一条微博数据的 id
                params["max_id"] = "\(status.id - 1)"
            }
            
        }else{
    
            //进入到这里说明是下拉刷新
            if let status = statusArray.first {
                params["since_id"] = "\(status.id)"
            }
        }
        
        
        
        //发送 get 请求
        manager.GET(urlString, parameters: params, success: { (dataTask, result) -> Void in
            //请求成功
            if let resultDic = result as? [String: AnyObject]{
                // 取出微博数据的数组
                let statusDics = resultDic["statuses"] as? [[String: AnyObject]]
                
                //创建一个临时数组
                var tempArray = [LXLStatus]()
                
                for statusDic in statusDics!{
                    //初始化模型
                    let status = LXLStatus(dictionary: statusDic)
                    tempArray.append(status)
                    
                }
                
                
                
                
                
                // 判读是否是上拉加载
                if self.pullupView.isAnimating(){
                    //如果是上拉加载,就将返回的新数据放到数组最后面
                    self.statusArray += tempArray
                }else{
                    //进入到这里说明是下拉刷新
                    //将数据添加到数组的前面
                    self.statusArray = tempArray + self.statusArray
                    
                    //显示下拉刷新的提示 label
                    if self.statusArray.count != 0{
                        self.showPullDownTips(tempArray.count)
                    }
                }
                
            
                //告诉 tableView,重新加载数据
                self.tableView.reloadData()
                
            }
            
            
                //停止刷新和加载
                self.endRefreshing()
            
            }) { (dataTask, error) -> Void in
                //  请求失败
                printLog("错误信息\(error)")
                SVProgressHUD.showInfoWithStatus("请求失败,请检查网络")
                
                self.endRefreshing()
        }
        
    }
    
    
    //结束刷新和加载的方法
    private func endRefreshing(){
        self.pullupView.stopAnimating()
        self.refreshControl?.endRefreshing()
    }
    
    
    
    
    //上拉加载的控件
    private lazy var pullupView:UIActivityIndicatorView = {
        let pullupView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        //停止的时候隐藏
//        pullupView.hidesWhenStopped = false
//        //开始动画
//        pullupView.startAnimating()
        
        //指定颜色
        pullupView.color = UIColor.orangeColor()
        
        return pullupView
    }()
    
  
    
    //下拉刷新的 label
    private func showPullDownTips(count: Int){
        //判断是否已正在显示,如果正在执行动画,就不让其再次执行动画
        if pullDownTipLabel.hidden == false{
            return
        }
        
        pullDownTipLabel.text = count == 0 ? "没有微博数据" : "\(count)条新微博"
        
        //执行动画
        let height: CGFloat = 35
        
        //让其显示
        pullDownTipLabel.hidden = false
        
        // 设置位置
        pullDownTipLabel.size = CGSizeMake(SCREENW, height)
        pullDownTipLabel.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - height
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            //调整 pullDownTipLabel 的 y 值
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, height)
            }) { (finish) -> Void in
                //执行回去的动画
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (finish) -> Void in
                        //动画执行完毕,隐藏
                        self.pullDownTipLabel.hidden = true
                })
        }
    }
    
    //下拉刷新的 label
    private lazy var pullDownTipLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        //设置字体大小
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.whiteColor()
        //文字居中
        label.textAlignment = NSTextAlignment.Center
        
        //设置文字
//        label.text = "没有新微博数据"
        
        //添加到 navigationBar的后面
        self.navigationController?.view.insertSubview(label, belowSubview: self.navigationController!.navigationBar)
        
        label.hidden = true
        
        return label
    }()
    


}

extension LXLHomeViewController{
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID, forIndexPath: indexPath)
        cell.textLabel?.text = statusArray[indexPath.row].text
        
        //如果当前 indexPath.row 等于最后一条数据,就去加载更多
        if indexPath.row == statusArray.count - 1 && !pullupView.isAnimating(){
            //进入到这个方法里面,代表当前是最后一条数据,加载更多
            pullupView.startAnimating()
            loadData()

        }
        
        return cell
    }
    
}

